package com.mifengs.mall.ui.main;


import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.FloatLayoutHelper;
import com.bumptech.glide.Glide;

import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.mall.adapter.ClassifyAdapter;
import com.mifengs.mall.adapter.FourGridFloAdapter;
import com.mifengs.mall.adapter.HomeBannerAdapter;
import com.mifengs.mall.adapter.HomeFiveFloorTypeAdapter;
import com.mifengs.mall.adapter.HomeFourFloorTypeAdapter;
import com.mifengs.mall.adapter.HomeMidAdapter;
import com.mifengs.mall.adapter.HomeOneFloorTypeAdapter;
import com.mifengs.mall.adapter.HomeThreeFloorTypeAdapter;
import com.mifengs.mall.adapter.HomeTitleAdapter;
import com.mifengs.mall.adapter.HomeTopAdapter;
import com.mifengs.mall.adapter.HomeTwoFloorTypeAdapter;
import com.mifengs.mall.adapter.SubAdapter;
import com.mifengs.mall.adapter.TwoFourFloAdapter;
import com.mifengs.mall.adapter.TwoGridFloAdapter;
import com.mifengs.mall.adapter.TwoThreeFloAdapter;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.di.component.DaggerHomeFrgComponent;
import com.mifengs.mall.di.module.HomeFrgModule;
import com.mifengs.mall.entity.BannerBean;
import com.mifengs.mall.entity.FloorBean;
import com.mifengs.mall.entity.HomeData;
import com.mifengs.mall.entity.MenuBean;
import com.mifengs.mall.entity.MqttMsg;
import com.mifengs.mall.entity.StoreApplyInfo;
import com.mifengs.mall.event.HomeFrgEvent;
import com.mifengs.mall.event.PushMsgEvent;
import com.mifengs.mall.ui.login.LoginActivity;
import com.mifengs.mall.ui.msg.MsgCenterActivity;
import com.mifengs.mall.ui.opencompany.OpenCompanyActivity;
import com.mifengs.mall.ui.openself.OpenSelfActivity;
import com.mifengs.mall.util.ImageLoadUtil;
import com.mifengs.mall.util.ToIntentUtil;
import com.mifengs.mall.util.UIUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.gavinliu.android.lib.shapedimageview.ShapedImageView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseFragment<HomePresenter> implements HomeContract.View, EasyPermissions.PermissionCallbacks, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.fl_top)
    FrameLayout mFlTop;
    @BindView(R.id.ll_top_bg)
    LinearLayout mLlTopBg;
    @BindView(R.id.iv_scan)
    ImageView mIvScan;
    @BindView(R.id.tv_scan)
    TextView mTvScan;
    @BindView(R.id.iv_message)
    ImageView mIvMessage;
    @BindView(R.id.tv_message)
    TextView mTvMessage;
    @BindView(R.id.ll_search)
    LinearLayout mLlSearch;
    @BindView(R.id.ll_top)
    LinearLayout mLlTop;
    @BindView(R.id.swipe_container)
    SwipeRefreshLayout mSwipeContainer;
    @BindView(R.id.rl_error)
    RelativeLayout mRlError;
    @BindView(R.id.btn_retry)
    TextView mBtnRetry;
    @BindView(R.id.spin)
    ImageView mWaitingView;
    @BindView(R.id.suspension_layout)
    LinearLayout mSuspensionLayout;
    @BindView(R.id.push_msg_img)
    ShapedImageView mPushMsgImg;
    @BindView(R.id.push_msg_text)
    TextView mPushMsgText;
    private static final int ONE_FLOOR_TEMPLATE = 1;
    private static final int TWO_FLOOR_TEMPLATE = 2;
    private static final int THREE_FLOOR_TEMPLATE = 3;
    private static final int FOUR_FLOOR_TEMPLATE = 4;
    private static final int FIVE_FLOOR_TEMPLATE = 5;
    private static final int SIX_FLOOR_TEMPLATE = 6;
    private static final int SEVEN_FLOOR_TEMPLATE = 7;
    private static final int EIGTH_FLOOR_TEMPLATE = 8;
    private static final int NICE_FLOOR_TEMPLATE = 9;
    private static final int TEN_FLOOR_TEMPLATE = 10;
    private static final int ELEVEN_FLOOR_TEMPLATE = 11;
    private static final int TWELVE_FLOOR_TEMPLATE = 12;
    public static final int REQUEST_PERMISSION_CAMERA = 1;
    public static final int REFRESH_DATA = 2;
    public static final int FIRSTGET_DATA = 1;
    private static final String TAG = "HomeFragment:";

    private int mWindowHeight;
    private HomeTopAdapter mHomeTopAdapter;
    private ClassifyAdapter mClassifyAdapter;
    private HomeMidAdapter mHomeMidAdapter;
    private HomeOneFloorTypeAdapter mHomeOneFloorTypeAdapter;
    private HomeTwoFloorTypeAdapter mHomeTwoFloorTypeAdapter;
    private HomeThreeFloorTypeAdapter mHomeThreeFloorTypeAdapter;
    private HomeFourFloorTypeAdapter mHomeFourFloorTypeAdapter;
    private HomeFiveFloorTypeAdapter mHomeFiveFloorTypeAdapter;

    private TwoFourFloAdapter mTwoFourFloAdapter;
    private TwoGridFloAdapter mTwoGridFloAdapter;
    private TwoThreeFloAdapter mTwoThreeFloAdapter;
    private FourGridFloAdapter mFourGridFloAdapter;
    private HomeBannerAdapter mHomeBannerAdapter;
    private HomeTitleAdapter mHomeTitleAdapter;

    private List<DelegateAdapter.Adapter> adapters;
    private List<DelegateAdapter.Adapter> mFloorAdapters;
    private DelegateAdapter delegateAdapter;
    private int mTopType = 1;
    private View view;
    private ScheduledExecutorService service;
    private MqttMsg mqttMsg;

    public HomeFragment() {
        // Required empty public constructor
    }


    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mSuspensionLayout.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    mSuspensionLayout.setVisibility(View.GONE);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initInjector() {
        DaggerHomeFrgComponent.builder()
                .homeFrgModule(new HomeFrgModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
//        EventBus.getDefault().register(this);
        init();
        return view;
    }

    private void init() {
        setSwipeContainer();
        setStatusBarHeight();
        WindowManager wm = getActivity().getWindowManager();
        mWindowHeight = wm.getDefaultDisplay().getHeight();
        Glide.with(this).load(R.drawable.ic_mifeng_progress).into(mWaitingView);
        mRvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int offset = mRvList.computeVerticalScrollOffset();
                int h = mWindowHeight / 3;
                if (offset < h) {
                    float f = (float) offset / (float) (h * 1.2);
                    mLlTopBg.setAlpha(f);
                    setTopBarColor(1);
                } else {
                    mLlTopBg.setAlpha(1);
                    setTopBarColor(2);
                }
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(getContext());
        mRvList.setLayoutManager(layoutManager);


        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRvList.setRecycledViewPool(viewPool);
        // viewPool.setMaxRecycledViews(20, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        mRvList.setAdapter(delegateAdapter);
        adapters = new LinkedList<>();
        mFloorAdapters = new LinkedList<>();
        mHomeTopAdapter = new HomeTopAdapter(getContext());
        mHomeMidAdapter = new HomeMidAdapter(getContext());
        mClassifyAdapter = new ClassifyAdapter(getContext());
        mHomeTitleAdapter = new HomeTitleAdapter(getContext());
        adapters.add(mHomeTopAdapter);
        adapters.add(mClassifyAdapter);
        adapters.add(mHomeMidAdapter);
        adapters.add(mHomeTitleAdapter);
        adapters.add(initFloatLayoutHelper());
        delegateAdapter.setAdapters(adapters);

//        mSuspensionLayout.getBackground().setAlpha(150);
//        service = Executors.newScheduledThreadPool(100);
//        service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 3, 5, TimeUnit.SECONDS);
//        service.scheduleAtFixedRate(new GoneScheduledExecutor(), 3, 10, TimeUnit.SECONDS);
        mPresenter.getData(FIRSTGET_DATA);
        mPresenter.getPhotoPath();
//        mSuspensionLayout.setVisibility(View.VISIBLE);
//        mSuspensionLayout.getBackground().setAlpha(200);


    }

    public SubAdapter initFloatLayoutHelper() {
        FloatLayoutHelper floatLayoutHelper = new FloatLayoutHelper();
//        floatLayoutHelper.setAlignType(TOP_RIGHT);
        int screenW = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        int scrennH = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        floatLayoutHelper.setDefaultLocation(screenW - 150, scrennH - 280);
        VirtualLayoutManager.LayoutParams layoutParams = new VirtualLayoutManager.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        SubAdapter fixLayoutAdapter = new SubAdapter(getContext(), floatLayoutHelper, layoutParams);
        return fixLayoutAdapter;
        }



        class VisibleScheduledExecutor implements Runnable {

            @Override
            public void run() {
//            mSuspensionLayout.setVisibility(View.VISIBLE);
                Message msg = new Message();
                msg.what = 1;
                mHandle.sendMessage(msg);
            }
        }

        class GoneScheduledExecutor implements Runnable {

            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 2;
                mHandle.sendMessage(msg);

            }
        }


    private void setSwipeContainer() {
        mSwipeContainer.setDistanceToTriggerSync(UIUtil.SwipeDistance); //设置手指移动多少触发刷新
        mSwipeContainer.setOnRefreshListener(this);
        mSwipeContainer.setOnChildScrollUpCallback(new SwipeRefreshLayout.OnChildScrollUpCallback() {

            @Override
            public boolean canChildScrollUp(SwipeRefreshLayout parent, @Nullable View child) {
                if (mRvList == null) {
                    return false;
                }
                VirtualLayoutManager virtualLayoutManager = (VirtualLayoutManager) mRvList.getLayoutManager();
                return virtualLayoutManager.findFirstCompletelyVisibleItemPosition() != 0;
            }
        });
    }

    private void setStatusBarHeight() {
        int statusHeight = UIUtil.getStatusHight();
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mLlTop.getLayoutParams();
        layoutParams.setMargins(0, statusHeight, 0, 0);
    }

    @Override
    public void setData(HomeData data) {

    }

    @Override
    public void setTopBanner(List<BannerBean> bannerBeanList) {
        mHomeTopAdapter.setBannerBeanList(bannerBeanList);
    }

    @Override
    public void setMenu(List<MenuBean> menuBeanList) {
        mClassifyAdapter.setMenuBeanList(menuBeanList);
    }

    @Override
    public void setMidViewData(Map<String, Object> datas) {
        mHomeMidAdapter.setDatas(datas);
    }


    int temp = 0;

    @Override
    public void setFloors(List<FloorBean> floorList) {
        try {
            delegateAdapter.removeAdapters(mFloorAdapters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mFloorAdapters.clear();
        for (int i = 0; i < floorList.size(); i++) {
            FloorBean floorBean = floorList.get(i);
            if (ONE_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                mHomeOneFloorTypeAdapter = new HomeOneFloorTypeAdapter(getContext());
                mFloorAdapters.add(mHomeOneFloorTypeAdapter);
                mHomeOneFloorTypeAdapter.setFloorData(floorBean);
            } else if (TWO_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                mHomeTwoFloorTypeAdapter = new HomeTwoFloorTypeAdapter(getContext());
                mFloorAdapters.add(mHomeTwoFloorTypeAdapter);
                mHomeTwoFloorTypeAdapter.setFloorData(floorBean);
            } else if (THREE_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                mHomeThreeFloorTypeAdapter = new HomeThreeFloorTypeAdapter(getContext());
                mFloorAdapters.add(mHomeThreeFloorTypeAdapter);
                mHomeThreeFloorTypeAdapter.setFloorData(floorBean);
            } else if (FOUR_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                mHomeFourFloorTypeAdapter = new HomeFourFloorTypeAdapter(getContext());
                mFloorAdapters.add(mHomeFourFloorTypeAdapter);
                mHomeFourFloorTypeAdapter.setFloorData(floorBean);
            } else if (FIVE_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                mHomeFiveFloorTypeAdapter = new HomeFiveFloorTypeAdapter(getContext());
                mFloorAdapters.add(mHomeFiveFloorTypeAdapter);
                mHomeFiveFloorTypeAdapter.setFloorData(floorBean, 1);

            } else if (SIX_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                //2*2
                mTwoGridFloAdapter = new TwoGridFloAdapter(getContext());
                mFloorAdapters.add(mTwoGridFloAdapter);
                mTwoGridFloAdapter.setFloorData(floorBean);
            } else if (SEVEN_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                //2+3
                mTwoThreeFloAdapter = new TwoThreeFloAdapter(getContext());
                mFloorAdapters.add(mTwoThreeFloAdapter);
                mTwoThreeFloAdapter.setFloorData(floorBean);
            } else if (EIGTH_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                //banner楼层
                mHomeBannerAdapter = new HomeBannerAdapter(getContext());
                mFloorAdapters.add(mHomeBannerAdapter);
                mHomeBannerAdapter.setBannerBeanList(floorBean.getBanners());
            } else if (NICE_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                //标题楼层
                mHomeTitleAdapter = new HomeTitleAdapter(getContext());
                mFloorAdapters.add(mHomeTitleAdapter);
                mHomeTitleAdapter.setFloorData(floorBean);

            } else if (TEN_FLOOR_TEMPLATE==floorBean.getTemplate()) {
                //2+2*2
                mTwoFourFloAdapter = new TwoFourFloAdapter(getContext());
                mFloorAdapters.add(mTwoFourFloAdapter);
                mTwoFourFloAdapter.setFloorData(floorBean);
            } else if (ELEVEN_FLOOR_TEMPLATE== floorBean.getTemplate()) {
//                4*1
                mFourGridFloAdapter = new FourGridFloAdapter(getContext());
                mFloorAdapters.add(mFourGridFloAdapter);
                mFourGridFloAdapter.setFloorData(floorBean);
            } else if (TWELVE_FLOOR_TEMPLATE== floorBean.getTemplate()) {
                mHomeFiveFloorTypeAdapter = new HomeFiveFloorTypeAdapter(getContext());
                mFloorAdapters.add(mHomeFiveFloorTypeAdapter);
                mHomeFiveFloorTypeAdapter.setFloorData(floorBean, 2);
            }

        }
        delegateAdapter.addAdapters(mFloorAdapters);
    }


    @Override
    public void stopRefreshView() {
        if (mSwipeContainer != null) {
            mSwipeContainer.setRefreshing(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mHomeMidAdapter != null) {
            mHomeMidAdapter.release();
        }

//        if(!service.isShutdown()){
//            service.shutdown();
//        }
    }


    private void setTopBarColor(int type) {
        switch (type) {
            case 2:
                //避免重复设置
                if (mTopType != 2) {
                    mTvScan.setTextColor(getResources().getColor(R.color.custom_mid_txt_color));
                    mTvMessage.setTextColor(getResources().getColor(R.color.custom_mid_txt_color));
                    mIvScan.setImageResource(R.drawable.ic_gray_scan);
                    mIvMessage.setImageResource(R.drawable.ic_gray_message);
                    mLlSearch.setBackgroundResource(R.drawable.shape_gray_search);
                    mTopType = 2;
                }
                break;
            case 1:
                if (mTopType != 1) {
                    mTvScan.setTextColor(getResources().getColor(R.color.white));
                    mTvMessage.setTextColor(getResources().getColor(R.color.white));
                    mIvScan.setImageResource(R.drawable.ic_scan);
                    mIvMessage.setImageResource(R.drawable.ic_message);
                    mLlSearch.setBackgroundResource(R.drawable.shape_search);
                    mTopType = 1;
                }
                break;
        }
    }

    @OnClick({R.id.rl_scan, R.id.ll_search, R.id.btn_retry, R.id.relativeLayout_msg, R.id.push_msg_text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_scan:
                needCamera();
                break;
            case R.id.ll_search:
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_retry:
                mPresenter.getData(FIRSTGET_DATA);
                break;
            case R.id.relativeLayout_msg:
                boolean isLogin = PreferenceUtils.getLoginStatus();
                if (isLogin) {
                    startActivity(new Intent(getContext(), MsgCenterActivity.class));
                } else {
                    startActivity(new Intent(MallApplication.getInstance(), LoginActivity.class));
                }
                break;
            case R.id.suspension_layout:
                if (mqttMsg != null)
                    ToIntentUtil.toCommonIntent(mqttMsg.getResults().getMessage().toString(), getContext());
                break;
            case R.id.push_msg_text:
                if (mqttMsg != null)
                    ToIntentUtil.toCommonIntent(mqttMsg.getResults().getMessage().toString(), getContext());
                break;
        }
    }

    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA)
    public void needCamera() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getActivity(), perms)) {
            startScan();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.need_camera_permission),
                    REQUEST_PERMISSION_CAMERA, perms);
        }
    }

    private void startScan() {
        Intent intent = new Intent(getContext(), ScanActivity.class);
        startActivity(intent);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public void onRefresh() {
        mPresenter.getData(REFRESH_DATA);
    }


    @Override
    public void showProgress() {
        mWaitingView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        mWaitingView.setVisibility(View.GONE);
    }


    @Override
    public void showNetError() {
        mRlError.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideNetError() {
        mRlError.setVisibility(View.GONE);
    }

    @Override
    public void startShopTypeActivity() {
//        Intent intent = new Intent(getActivity(), ShopTypeActivity.class);
//        startActivity(intent);
        ToIntentUtil.toCommonIntent(Constant.H5_STORE_APPLY_NOTICE,getActivity());
    }

    @Override
    public void startOpenShopActivity(int type,int storeStatus, StoreApplyInfo info) {
        if(type==0){
            Intent intent = new Intent(getActivity(),OpenSelfActivity.class);
            intent.putExtra("StoreApplyInfo",info);
            startActivity(intent);
        }else if(type==1){
            Intent intent = new Intent(getActivity(),OpenCompanyActivity.class);
            intent.putExtra("StoreApplyInfo",info);
            startActivity(intent);
        }
    }

    @Override
    public void startLoginActivity() {
        Intent intent = new Intent(getActivity(),LoginActivity.class);
        startActivity(intent);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(PushMsgEvent event) {
        switch (event.action){
            case PushMsgEvent.MOPAO_MSG:
                mqttMsg = event.getMqttMsg();
                mSuspensionLayout.getBackground().setAlpha(150);
                mSuspensionLayout.setVisibility(View.VISIBLE);
                ImageLoadUtil.displayImage(getContext(), mqttMsg.getResults().getImageurl().trim(), mPushMsgImg);
                mPushMsgText.setText(mqttMsg.getResults().getMessage().toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.what = 2;
                        mHandle.sendMessage(msg);
                    }
                }).start();
                break;
            case PushMsgEvent.VOICE_MSG:

                break;

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeEvent(HomeFrgEvent event) {
        switch (event.action){
            case HomeFrgEvent.OPENSHOP:
                if(PreferenceUtils.getLoginStatus()){
                    mPresenter.getApplyProgress();
                }else{
                    Intent intent = new Intent(getActivity(),LoginActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    

}
